import os.path

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from conf import conf
from tools.framework import get_ui_value, gen_result_folder_name
from tools.file_manager import gen_data_name
from core.constant import *
from module.static_module.parent.model import AdditionModule

matplotlib.use("Agg")

# 设置字体属性，确保中文正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体为SimHei，这是一个支持中文的字体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class ComparisonChartModel(AdditionModule):
    def __init__(self, master):
        super().__init__(master, Module.ComparisonChart)
        # 实体类映射视图类变量数据
        self.mk_data_file_ls = []  # 行情文件
        self.symbol_name_ls = []  # 标的名称

        # 映射视图类变量数据默认值
        self.mk_data_file = []  # 行情文件
        self.symbol_name = []  # 标的名称

        # 实体类结构变量
        self.sub_view = None

        self.draw_num = int((
                                    conf.AdditionModule.visualization_x_px.value - conf.AdditionModule.axis_y_px.value) // conf.AdditionModule.k_px.value)
        self.draw_data: pd.DataFrame = None

    def sec_init(self):
        # 实体类映射视图类变量数据
        self.mk_data_file_ls = []  # 行情文件
        self.symbol_name_ls = []  # 标的名称

        from module.addition_module.comparison_chart.view import ComparisonChartView
        self.sub_view = ComparisonChartView(self)

    def get_ui_params(self):
        # 获取ui界面的相关参数
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.MkDataFile)
        self.mk_data_file = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.SymbolName)
        self.symbol_name = get_ui_value(values, indices, WidgetCategory.Entry)

    def on_draw(self):
        self.get_ui_params()
        # 加载行情数据
        mk_data_dc: dict = self.master.file_manager.read_dc_csv(self.mk_data_file)
        first_key = list(mk_data_dc.keys())[0]
        # 选择要绘制的行情数据
        if self.symbol_name:
            symbol_ls = self.symbol_name.split(",")
        else:
            symbol_ls = list(mk_data_dc.keys())
        # 筛选部分样本数据进行绘制
        new_mk_data_dc = {}
        indices = np.linspace(0, len(mk_data_dc[first_key]) - 1, self.draw_num).astype(int)
        for symbol_o in symbol_ls:
            if symbol_o in mk_data_dc.keys():
                mk_data = mk_data_dc[symbol_o]
                equity_data_sampled = mk_data.iloc[indices]
                new_mk_data_dc[symbol_o] = equity_data_sampled

        self.draw_data = new_mk_data_dc
        # 生成数据指标并输出到控制台
        category_ls = list(mk_data_dc.keys())
        print("|    名称    | 收益率（近一年） | 风险率（近一年） | 最大回撤 |")
        print("|:--------:|:---------|:--------:|:----:|")
        for category_o in category_ls:
            draw_data_o = mk_data_dc[category_o]
            # 总收益率
            total_return = draw_data_o["close"].iloc[-1] / draw_data_o["close"].iloc[0] - 1
            # 风险率
            volatility = np.std(draw_data_o["close"]) / draw_data_o["close"].iloc[-1]

            # 最大回撤
            rolling_max = draw_data_o["close"].cummax()
            daily_drawdown = draw_data_o["close"] / rolling_max - 1
            max_drawdown = -daily_drawdown.min()

            yield_rate = str(round(total_return * 100, 2)) + '%'
            risk_rate = str(round(volatility * 100, 2)) + '%'
            max_withdrawal = str(round(max_drawdown * 100, 2)) + '%'
            # 将结果存储在字典中
            result = {
                'name': category_o,
                'returns': yield_rate,
                'volatility': risk_rate,
                'max_drawdown': max_withdrawal
            }
            returns_str = result['returns']
            volatility_str = result['volatility']
            max_drawdown_str = result['max_drawdown']
            print(f"|   {result['name']}   |  {returns_str}  |   {volatility_str}    |  {max_drawdown_str}  |")

        # 绘制
        self.sub_view.draw_dynamic_graph()

        pass


